package com.cxf.ws.util;

import java.net.URL;

import org.apache.axis.client.Service;
import org.apache.axis.client.Stub;

import com.cmbc.cos.cbs.wsclient.WsClientConfig;

public class WsClientUtil {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Service getLocator(String serviceName) throws Exception {
        String className = WsClientConfig.getWebServiceConfig(serviceName, "locator");
        Class classObj = Class.forName(className);
        Service service = (Service) classObj.getConstructor().newInstance();
        RPCHandlerUtil.registerHandler(service, LogSOAPMessageRPCHandler.class);
        return service;
    }

    public static Stub getStub(String serviceName) throws Exception {
        String className = WsClientConfig.getWebServiceConfig(serviceName, "stub");
        String port = WsClientConfig.getWebServiceConfig(serviceName, "port");
        String urlStr = WsClientConfig.getWebServiceUrl(serviceName);
        int timeout = WsClientConfig.getReceiveTimeout(serviceName);
        Service service = new org.apache.axis.client.Service();
        URL url = new URL(urlStr);
        Stub stub = (Stub) Class.forName(className).getConstructor(URL.class, javax.xml.rpc.Service.class)
                .newInstance(url, service);
        stub.setPortName(port);
        stub.setTimeout(timeout);
        RPCHandlerUtil.registerHandler(service, port, LogSOAPMessageRPCHandler.class);
        return stub;
    }
    /**
     * 获取webservices stub
     * @param serviceName 服务名称
     * @param adress ip-port地址
     * @return
     * @throws Exception
     */
    public static Stub getStub(String serviceName,String adress) throws Exception {
        String className = WsClientConfig.getWebServiceConfig(serviceName, "stub");
        String port = WsClientConfig.getWebServiceConfig(serviceName, "port");
        String serverName = WsClientConfig.getConfigValue(serviceName + ".server");
        String serviceUrl =  WsClientConfig.getConfigValue(serviceName + ".url");
        serviceUrl = serviceUrl.replace("$" + serverName, adress);
        int timeout = WsClientConfig.getReceiveTimeout(serviceName);
        Service service = new org.apache.axis.client.Service();
        URL url = new URL(serviceUrl);
        Stub stub = (Stub) Class.forName(className).getConstructor(URL.class, javax.xml.rpc.Service.class)
                .newInstance(url, service);
        stub.setPortName(port);
        stub.setTimeout(timeout);
        RPCHandlerUtil.registerHandler(service, port, LogSOAPMessageRPCHandler.class);
        return stub;
    }
}
